package com.fivefaces.ide.plugins.impl;

import com.fivefaces.ide.plugins.CommandBuilder;
import com.fivefaces.ide.plugins.ConsoleExecutablePathService;
import com.fivefaces.ide.plugins.Constants;
import com.fivefaces.ide.plugins.FileUtils;
import com.intellij.openapi.diagnostic.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * User: abdullahkhan
 * Date: 13/09/12
 * Time: 6:27 PM
 */
abstract class AbstractCommandBuilder implements CommandBuilder {
    protected final Logger logger = Logger.getInstance(getClass());
    protected final ConsoleExecutablePathService consoleExecutablePathService;

    protected AbstractCommandBuilder(ConsoleExecutablePathService consoleExecutablePathService) {
        this.consoleExecutablePathService = consoleExecutablePathService;
    }


    @Override
    public String[] buildCommand(String filePath) {
        return new String[]{writeScriptFile(filePath)};
    }

    protected abstract FileWriter writeFile(String path, FileWriter fileWriter, File executeFile) throws IOException;

    protected String writeScriptFile(String path) {
        String result = null;
        FileWriter fileWriter = null;
        try {
            File executeFile = buildTempExecutablePath();
            fileWriter = writeFile(path, fileWriter, executeFile);
            result = executeFile.getAbsolutePath();
            makeFileExecutable(result);
        } catch (IOException e) {
            logger.error("Failed to write file", e);
        } finally {
            FileUtils.close(fileWriter);
        }
        return result;
    }

    protected void makeFileExecutable(String result) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("chmod", "a+x", result);
            processBuilder.redirectErrorStream();
            processBuilder.start();
        } catch (IOException e) {
            logger.error("Failed to make file executable.", e);
        }
    }

    protected File buildTempExecutablePath() {
        String tempDir = System.getProperty("java.io.tmpdir");
        return new File(tempDir + File.separator + System.currentTimeMillis() + getFileExtension());
    }

    protected String getFileExtension() {
        return Constants.UNIX_EXTENSION;
    }

    protected String getExecutablePath() {
        return consoleExecutablePathService.findPath();
    }
}
